package com.zet.etchat.demo;

import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import java.net.Proxy;

public class Demo {
    public static void main(String[] args) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new java.net.InetSocketAddress("localhost",7890));
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new OpenAILogger());
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient
                .Builder()
                .proxy(proxy)
                // 自定义日志输出
                .addInterceptor(logging)
                // 自定义返回值拦截
                .addInterceptor(new OpenAiResponseInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey(List.of("sk-xxx"))
                .okHttpClient(client)
                .build();

        List<Message> messages = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入对话内容：");
            String input = scanner.nextLine();
            if (input.equals("exit")) {
                break;
            }
            if (input.isEmpty() || input.isBlank()){
                System.out.println("请输入对话内容：");
                continue;
            }
            Message message = Message.builder().role(Message.Role.USER).content(input).build();
            messages.add(message);
            ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build();
            ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
            System.out.println(chatCompletionResponse);
            chatCompletionResponse.getChoices().forEach(choice -> {
                System.out.println("AI回复：" + choice.getMessage().getContent());
            });
        }
    }


}
